package com.example.timerecorder;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.ArrayList;

public class SelectTagActivity extends AppCompatActivity {

    public static final int RESULT_CODE_ADD_TAG = 4;
    public static final int RESULT_CODE_ALTER_TAG = 10;
    private static final String TAG = "selectTagActivity";

    private ListView tagList;
    EditText editTag;
    LinearLayout createTagLinearLayout;
    TextView createTag;
    ImageView createTagImage;

    String selectTag, flag;
    ArrayList<String> tagStrList, filterList;

    private static TagAdapter tagAdapter;
    DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_tag);

        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        editTag = findViewById(R.id.editTag);
        tagList = findViewById(R.id.tagList);
        createTag = findViewById(R.id.createTag);
        createTagImage = findViewById(R.id.createTagImage);
        createTagLinearLayout = findViewById(R.id.createTagLinearLayout);

        selectTag = "";

        //使用intent接收当前选择tag，flag标志从哪个页面进入
        Intent intent = getIntent();
        selectTag = intent.getStringExtra("current_tag");
        flag = intent.getStringExtra("flag");

        //从数据库获得当前不同tag
        dbManager = new DBManager(SelectTagActivity.this);
        tagStrList = dbManager.listAllTag();
        Log.i(TAG, "onCreate: 查询所有tag");

        Log.i(TAG, "afterTextChanged: 用户尚未输入，显示所有tag");
        //显示所有tag
        if(tagStrList.size()>0){
            //使用自定义适配器
            tagAdapter = new TagAdapter(SelectTagActivity.this, R.layout.list_tag, tagStrList);
            tagAdapter.defaultTagColor();
            tagAdapter.setSelectTag(selectTag);
            tagList.setAdapter(tagAdapter);
            setListViewHeightBasedOnChildren(tagList, 0);
        }
        editTag.addTextChangedListener(textWatcher);

        //获取当前选择的tag
        tagList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                tagAdapter.changeSelected(position);
                selectTag = (String)tagAdapter.getItem(position);
                Log.i(TAG, "setOnItemClickListener: tagStr:" + selectTag);
            }
        });


    }

    //editView变化监听器
    final private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            if(str.length()>0){
                Log.i(TAG, "afterTextChanged: 用户在输入框内有输入");
                //清除现有adpter中内容
                tagList.setAdapter(null);
                setListViewHeightBasedOnChildren(tagList, 1);
                createTagLinearLayout.setVisibility(View.GONE);
                //筛选tag
                filterList = testPartContain(str, tagStrList);
                //考虑筛选or创建
                if(filterList.size() > 0){
                    Log.i(TAG, "afterTextChanged: 搜索有内容，现有tag中有用户输入部分");
                    tagAdapter = new TagAdapter(
                            SelectTagActivity.this,
                            R.layout.list_tag,
                            filterList
                    );
                    tagAdapter.defaultTagColor();
                    tagAdapter.setSelectTag(selectTag);
                    tagList.setAdapter(tagAdapter);
                    setListViewHeightBasedOnChildren(tagList, 0);

                    if(!filterList.contains(str)){
                        //没有完全相同tag
                        Log.i(TAG, "afterTextChanged: 包含部分tag，显示创建");
                        //包含部分tag，显示创建
                        createTagLinearLayout.setVisibility(View.VISIBLE);
                        createTag.setText(str);
                    }

                }else{
                    Log.i(TAG, "afterTextChanged: 不包含tag，显示创建");
                    //不包含，显示创建
                    createTagLinearLayout.setVisibility(View.VISIBLE);
                    createTag.setText(str);
                }
            }
            else{
                Log.i(TAG, "afterTextChanged: 用户无输入，显示所有tag");
                createTagLinearLayout.setVisibility(View.GONE);
                tagList.setAdapter(null);
                setListViewHeightBasedOnChildren(tagList, 1);

                Log.i(TAG, "afterTextChanged: selectTag:"+selectTag);

                //显示所有tag
                if(tagStrList.size()>0){
                    tagAdapter = new TagAdapter(
                            SelectTagActivity.this,
                            R.layout.list_tag,
                            tagStrList
                    );
                    tagAdapter.defaultTagColor();
                    tagAdapter.setSelectTag(selectTag);
                    tagList.setAdapter(tagAdapter);
                    setListViewHeightBasedOnChildren(tagList, 0);
                }
            }
        }
    };

    //点击√创建标签
    public void createTagClick(View tagImage) {
        //插入一条只有tag的记录，其他属性为空
        String createTagStr = createTag.getText().toString();
        if(!createTagStr.equals("")){
            Item item = new Item();
            item.setTag(createTagStr);
            DBManager dbManager = new DBManager(this);
            dbManager.add(item);
            Log.i("db","新增只有tag的记录");
            Toast.makeText(this, R.string.createTagSuccessTip, Toast.LENGTH_SHORT).show();

            tagStrList = dbManager.listAllTag();
            Log.i(TAG, "onCreate: 创建tag后，更新所有tag");

            //清除现有adpter中内容
            tagList.setAdapter(null);
            setListViewHeightBasedOnChildren(tagList, 1);
            createTagLinearLayout.setVisibility(View.GONE);
            //筛选tag，显示tag列表
            filterList = testPartContain(createTagStr, tagStrList);
            Log.i(TAG, "afterTextChanged: 搜索有内容，现有tag中有用户输入部分");
            tagAdapter = new TagAdapter(
                    SelectTagActivity.this,
                    R.layout.list_tag,
                    filterList
            );
            tagAdapter.defaultTagColor();
            tagAdapter.setSelectTag(selectTag);
            tagList.setAdapter(tagAdapter);
            setListViewHeightBasedOnChildren(tagList, 0);
        }

    }

    //检测ArrayList<String>部分包含
    public ArrayList<String> testPartContain(String str, ArrayList<String> list){
        ArrayList<String> resList = new ArrayList<>();
        for(int i=0; i<list.size(); i++){
            if(list.get(i).contains(str)){
                resList.add(list.get(i));
            }
        }
        return resList;
    }

    //点击Save保存选择标签
    public void saveTagClick(View btn){

        // 获取当前选择的tag
        if(selectTag==null || selectTag.equals("")){
            Log.i(TAG, "saveTagClick: 尚未选择任何tag");
            Toast.makeText(this, R.string.noSelectTagTip, Toast.LENGTH_SHORT).show();
        }else{
            //该界面有两种出现情况，添加记录和修改记录
            if(flag.equals("add")){
                //intent——将selectTag从activity传到mainActivity的fragment中
                Intent submitTag = new Intent(this, MainActivity.class);
                submitTag.putExtra("select_tag", selectTag);
                Log.i(TAG, "onClick: submitTag:" + selectTag);
                setResult(RESULT_CODE_ADD_TAG, submitTag);
            }
            if(flag.equals("alter")){
                //intent——将selectTag从activity传到alterRecordActivity中
                Intent alterTag = new Intent(this, AlterRecordActivity.class);
                alterTag.putExtra("select_tag", selectTag);
                Log.i(TAG, "onClick: alterTag:" + selectTag);
                setResult(RESULT_CODE_ALTER_TAG, alterTag);
            }
            finish();
        }
    }

    //动态设置ListView的高度
    public static void setListViewHeightBasedOnChildren(ListView listView, int flag) {
        if(listView == null) return;
        if (tagAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        //flag——setAdapter(null)时，为1
        if(flag == 0){
            for (int i = 0; i < tagAdapter.getCount(); i++) {
                View listItem = tagAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (tagAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    //设置返回
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }
}